package com.glory.dgcpcpda.activity.technicalservice;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.PartReplaceListAdapter;
import com.glory.dgcpcpda.adapter.RepairLogListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.base.Constant;
import com.glory.dgcpcpda.entity.AdrefListEntity;
import com.glory.dgcpcpda.entity.RepairFromListEntity;
import com.glory.dgcpcpda.entity.RepairSheetDataEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class TestFaultRegisterActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvEqp)
    TextView tvEqp;
    @BindView(R.id.tvRepairType)
    TextView tvRepairType;
    @BindView(R.id.tvPriority)
    TextView tvPriority;
    @BindView(R.id.tvFaultDesc)
    TextView tvFaultDesc;
    @BindView(R.id.tvLotID)
    TextView tvLotID;
    @BindView(R.id.tvFaultDemand)
    TextView tvFaultDemand;
    @BindView(R.id.ivFaultDemandArrow)
    ImageView ivFaultDemandArrow;
    @BindView(R.id.flFaultDemandList)
    FrameLayout flFaultDemandList;
    @BindView(R.id.etRepairDesc)
    FreeUI_ClearEditText etRepairDesc;
    @BindView(R.id.tvStartRepair)
    TextView tvStartRepair;
    @BindView(R.id.tvStartRepair2QC)
    TextView tvStartRepair2QC;
    @BindView(R.id.tvToEqp)
    TextView tvToEqp;
    @BindView(R.id.tvToProcess)
    TextView tvToProcess;
    @BindView(R.id.tvAdd)
    TextView tvAdd;
    @BindView(R.id.tvLocation)
    TextView tvLocation;
    @BindView(R.id.list_titleLayout)
    LinearLayout listTitleLayout;
    @BindView(R.id.rvReplacePartList)
    RecyclerView rvReplacePartList;
    @BindView(R.id.rvFaultLog)
    RecyclerView rvFaultLog;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.llBtnLayout)
    LinearLayout llBtnLayout;
    @BindView(R.id.llRepairDescLayout)
    LinearLayout llRepairDescLayout;
    private RepairFromListEntity.RepairData mData;
    private PartReplaceListAdapter mPartAdapter;
    private List<String> mRepairTypeList;
    private FreeUI_GeneralPop mRepairTypePop;
    private String mFrom = "";
    private  AdrefListEntity bodyAlarm;
    @Override
    protected int getLayoutResId() {
        return R.layout.activity_fault_register_test;
    }

    @Override
    protected void initView() {
        setMainLayout(llMain);
        tvBaseSubmit.setVisibility(View.GONE);
        mRepairTypeList = new ArrayList<>();
        tvTitle.setText("测试故障维修登记");
        Bundle bundle = getIntent().getExtras();
        mData = (RepairFromListEntity.RepairData) bundle.getSerializable("REPAIRFROM");
        mFrom = bundle.getString("FROM");
        tvFaultDemand.setText(mData.getREPAIRSHEETDATA().getTROUBLECODE());
        tvEqp.setText(mData.getREPAIRSHEETDATA().getEQUIPMENTID());
        tvLocation.setText(mData.getREPAIRSHEETDATA().getLOCATION());
        tvRepairType.setText(getType(mData.getREPAIRSHEETDATA().getREPAIRTYPE()));
        tvPriority.setText(mData.getREPAIRSHEETDATA().getPRIORITY());
        tvFaultDesc.setText(mData.getREPAIRSHEETDATA().getTROUBLECOMMENT());
        tvLotID.setText(mData.getREPAIRSHEETDATA().getLOTID());
        tvStartRepair.setText(mData.getREPAIRFORM().getSTATUS().equals("START") ? "开始维修" : "维修完成");
        etRepairDesc.setText(mData.getREPAIRSHEETDATA().getREPAIRCOMMENT());
        initRecyclerView(rvFaultLog,this);
        initRecyclerView(rvReplacePartList,this);
        RepairLogListAdapter mRepairLogAdapter = new RepairLogListAdapter(mData.getREPAIRFORMHISLIST());
        mRepairLogAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mRepairLogAdapter.isFirstOnly(true);
        rvFaultLog.setAdapter(mRepairLogAdapter);
        mPartAdapter = new PartReplaceListAdapter(mData.getPARTSLINEDATAS());
        mPartAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mPartAdapter.isFirstOnly(true);
        rvReplacePartList.setAdapter(mPartAdapter);
        llRepairDescLayout.setVisibility(mData.getREPAIRFORM().getSTATUS().equals("START") ? View.GONE : View.VISIBLE);
        tvAdd.setVisibility(mData.getREPAIRFORM().getSTATUS().equals("START") ? View.GONE : View.VISIBLE);
        if (mFrom != null && mFrom.equals("QC")){
            updateUI();
        }
        if (mData.getREPAIRFORM().getSTATUS().equals("STARTFORM")){
            tvToEqp.setVisibility(View.GONE);
            tvToProcess.setVisibility(View.GONE);
        }

    }

    private void updateUI() {
        llBtnLayout.setVisibility(View.GONE);
        tvBaseSubmit.setVisibility(View.GONE);
        tvAdd.setVisibility(View.GONE);
        etRepairDesc.setEnabled(false);
        flFaultDemandList.setEnabled(false);
    }

    private String getType(String repairtype) {
        String type = "";
        switch (repairtype){
            case "normal":
                type = "一般故障";
                break;
            case "eqp":
                type = "设备故障";
                break;
            case "program":
                type = "工艺问题";
                break;
            case "changeProducct":
                type = "换产品";
                break;
            case "changeMaterial":
                type = "换材料";
                break;
            case "changeTool":
                type = "换Tooling";
                break;
            case "Testprogram":
                type = "程序问题";
                break;
            default:
                type = "未知错误";
                break;
        }
        return type;
    }

    @Override
    protected void initData() {
        FreeUI_EntityCallBack<BaseResponseBean<AdrefListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<AdrefListEntity>>
                (new TypeToken<BaseResponseBean<AdrefListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    List<AdrefListEntity.Adref> adreflist = response.body().getResponse().getBody().getADREFLIST();
                    if (adreflist.size() > 0){
                        for (AdrefListEntity.Adref entity : adreflist)  {
                            mRepairTypeList.add(entity.getKEY() + "/" + entity.getTEXT());
                        }
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"ADREFLISTQUERY");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("REFERENCETYPE","USER");
        map.addProperty("REFERENCENAME","CPC_EQP_FAILURE_TYPE");
        NetUtils.requestPostNet("CPC.ADREFLISTQUERY","ADREFLISTQUERY",this,map,callBack);

        FreeUI_EntityCallBack<BaseResponseBean<AdrefListEntity>> callBack1 = new FreeUI_DialogEntityCallBack<BaseResponseBean<AdrefListEntity>>
                (new TypeToken<BaseResponseBean<AdrefListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    AdrefListEntity body = response.body().getResponse().getBody();
                    bodyAlarm = body;
                    tvFaultDesc.setText(body.getALARMCODE() + "/" + body.getALARMMSG() + "/" + body.getALARMTIME());
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"ADREFLISTQUERY");

            }
        };
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("EQPID",tvEqp.getText().toString());
        NetUtils.requestPostNet("CPC.GetEqpAlarmReport","GetEqpAlarmReport",this,jsonObject,callBack1);
    }


    @OnClick({R.id.tvStartRepair, R.id.tvAdd,R.id.tvToEqp,R.id.tvToProcess,R.id.tvStartRepair2QC})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flFaultDemandList:
                if (mRepairTypeList.size() <= 0){
                    showToast("未获取到维修故障信息列表",false);
                    return;
                }
                //维修故障类型
                if (mRepairTypePop != null) {
                    if (mRepairTypePop.isShowing()) {
                        mRepairTypePop.dismiss();
                    }
                } else {
                    mRepairTypePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flFaultDemandList.getWidth(), mRepairTypeList, ivFaultDemandArrow, (codeS, i) -> {
                        tvFaultDemand.setText(codeS);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivFaultDemandArrow);
                mRepairTypePop.showAsDropDown(flFaultDemandList, 0, 0);
                break;
            case R.id.tvStartRepair:
                //开始维修、维修完成
                showSubmitDialog(() -> requestForType(tvStartRepair.getText().toString().equals("开始维修") ? "STARTFORM" : "EXECUTE",""));
                break;
            case R.id.tvStartRepair2QC:
                if(tvStartRepair.getText().toString().equals("开始维修")){
                    showToast("未开始维修，不能转QC", false);
                    return;
                }
                //维修完成转QC
                showSubmitDialog(() -> requestForType( "EXECUTE","transforToQC"));
                break;
            case R.id.tvToEqp:
                requestForType("TRANSFOR","transforToEqp");
                break;
            case R.id.tvToProcess:
                //转技术员
                requestForType("TRANSFOR","transforToTe");
                break;
            case R.id.tvAdd:
                //部件更换
                Intent intent = new Intent(this,ReplacePartActivity.class);
                intent.putExtra("EQPID",tvEqp.getText().toString());
                startActivityForResult(intent,10001);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 10001){
            if (data != null){
                RepairSheetDataEntity.PartListEntity entity =
                        (RepairSheetDataEntity.PartListEntity) data.getSerializableExtra("PARTENTITY");
                mPartAdapter.addData(entity);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    private void requestForType(String type,String repairType){
        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                    if (type.equals("STARTFORM")){
                        showToast("开始维修成功",true);
                        tvStartRepair.setText("维修完成");
                        llRepairDescLayout.setVisibility(View.VISIBLE);
                        mData.getREPAIRFORM().setSTATUS("STARTFORM");
                        mData.getREPAIRSHEETDATA().setSTARTREPAIRTIME(FreeApi_DateUtils.getNowStringDate("yyyy/MM/dd HH:mm:ss"));
                        mData.getREPAIRSHEETDATA().setREPAIROWNER(Constant.CURRENT_USER);
                    }else {
                        showConfirmDialog(TestFaultRegisterActivity.this,"提交成功");
                    }

                }
            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(),"PMSREPAIR");

            }
        };
        JsonObject map = new JsonObject();
        if("transforToQC".equals(repairType)){
            map.addProperty("QC","Y");
            repairType="";
        }
        map.addProperty("ACTIONTYPE",type);
        map.addProperty("REPAIRTYPE",repairType);
        map.add("REPAIRFORM",new JsonParser().parse(new Gson().toJson(mData.getREPAIRFORM())).getAsJsonObject());
        RepairSheetDataEntity repairsheetdata = mData.getREPAIRSHEETDATA();
        if (bodyAlarm != null){
            repairsheetdata.setTROUBLETIME(bodyAlarm.getALARMTIME());
            repairsheetdata.setTROUBLECOMMENT(bodyAlarm.getALARMMSG());
        }
        if (!tvFaultDemand.getText().toString().equals("")){
           repairsheetdata.setTROUBLECODE(tvFaultDemand.getText().toString().split("/")[0]);

        }
        if (!type.equals("STARTFORM")){
            repairsheetdata.setREPAIRCOMMENT(getText(etRepairDesc));
        }
        mData.setPARTSLINEDATAS(mPartAdapter.getData());
        map.add("REPAIRSHEETDATA",new JsonParser().parse(new Gson().toJson(repairsheetdata)).getAsJsonObject());
        NetUtils.mRequestPostNet("CPC.PMSREPAIR", mData.getName(),"PMSREPAIR",this,map,callBack);

    }

}
